#!/usr/bin/ruby -d


require 'tstorage'
require '/var/lib/gems/1.8/gems/chronic-0.2.3/lib/chronic'
require 'logger'
require 'tstorage'
require 'mailread'


class TaskMgr
  ADMIN = "my.home.my.castle@gmail.com"
  ENVI = "LIVE" # LIVE or DEV environment. DEV === tests.noneo.is-a-geek.org
  def initialize
    log = Logger.new(STDOUT)
    log.level = Logger::INFO # DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
    $global_storage = TaskStorage.instance
  end
end


class TMail < TaskMgr

  def initialize(m)
    @msg = Mail.new(m)
  end

  def process
    if (@msg.header['From'] =~ /<(\S+@\S+)>/)
      @submitter = $1
    else
      Reminder.new(ADMIN, "WARNING: #{@msg.header['From']} sent us an e-mail.").send
    end
    @subject   = @msg.header['Subject']
    @request   = @msg.header['To']
    if @request =~ /submit/i 
      @submit = 1
    elsif @request =~ /remind/i
      @submit = 0
    else
      Reminder.new(@submitter, "WARNING: address not supported.").send
    end

    @date = nil
    @msg.body.each do |line|
      break if (line =~ /--\n/ || line =~ /^thank\w*\n/)
      if line =~ /^Date:\s*(.+)$/i
        something = $1
        if !(@date = Chronic.parse(something).to_i)
          Reminder.new(@submitter, "WARNING: date format not supported.").send
        end
      end
    end
    if !(@date)
      Reminder.new(@submitter, "WARNING: no supported directives.").send
    end
    if @submit
      $global_storage.store(@submitter, @subject, @date)
    else
      rem = Reminder.new(@submitter, @subject)
      smtp_code = rem.send
      if (smtp_code =~ /^2/)
        logger.info("Reminder for #{@submitter} sent.
                    SMTP response: #{smtp_code}")
      else
        logger.warn("Reminder for #{@submitter} NOT sent.
                    SMTP response: #{smtp_code}")
      end
    end
  end
end

